#include "log.h"

errno_t openLogFile(FILE** pFile, const char* filename, const char* mode)
{
	closeLogFile(*pFile);

	if (filename == NULL || strlen(filename) == 0)
	{
		printf("%s\n", "filename is null or empty");
		return -1;
	}

	errno_t result = fopen_s(pFile, filename, mode);
	if (result != 0)
	{
		printf("openLogFile result is : %d\n", result);
	}

	return result;
}

void saveLogInformation(FILE* pFile, void* log, int size)
{
	if (pFile != NULL)
	{
#ifdef ONLY_PRINT_LOG
		printf("%s", (char*)log);
#else
		fwrite(log, size, 1, pFile);
#endif
	}
	else
	{
		printf("saveLogInformation file pointer is NULL\n");
	}
}

void saveLogInformationAutoLine(FILE* pFile, void* log, int size)
{
	if (pFile != NULL)
	{
#ifdef ONLY_PRINT_LOG
		printf("%s\n", (char*)log);
#else
		if (size > 0)
		{
			fwrite(log, size, 1, pFile);
		}
		fwrite("\n", 1, 1, pFile);
#endif
	}
	else
	{
		printf("saveLogInformation file pointer is NULL\n");
	}
}

void closeLogFile(FILE* pFile)
{
	if (pFile != NULL)
	{
		fclose(pFile);
		pFile = NULL;
	}
}

void saveBufferToFile(void* buf, const char* filename, int size)
{
	FILE* pFile = NULL;

	openLogFile(&pFile, filename, "wb+");

	saveLogInformation(pFile, buf, size);

	closeLogFile(pFile);
}